<template>
  <!-- 展示每一条历史记录 -->
  <div class="image-history-view" v-if="showingHistory">
    <el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0" @row-click="handleRowClick">
      <el-table-column label="图片">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <img :src="scope.row.encode_detected_img" style="width: 100px; height: 100px">
          </div>
        </template>
      </el-table-column>
      <el-table-column label="图片名称" prop="name"></el-table-column>
      <el-table-column label="保存时间" prop="save_datetime"></el-table-column>
      <el-table-column label="模型名称" prop="model_name"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="danger" @click="deleteRow(scope.row, $event)">删除记录</el-button>
          <!-- <el-button type="primary" @click="handleRowClick(scope.row, scope.column, $event)">查看</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="prev, pager, next" :total="total_count" :page-size="PAGE_SIZE"
      :current-page="current_page" @update:current-page="handlePageChange" />
  </div>
  <!-- 展示选择的历史信息 -->
  <div class="image-show-view" v-else>
    <el-button color="#626aef" @click="showingHistory = true" style="margin-right: 20px;">返回</el-button>
    <span style="margin-right: 20px;">视频名称：{{ image.name }}</span>
    <span style="margin-right: 20px;">模型名称：{{ image.model_name }}</span>
    <div class="image-container">
      <div class="image-item">
        <h3>当前图片</h3>
        <img class="detect-image" :src="image.url" alt="当前图片">
      </div>
      <div class="image-item">
        <h3>检测结果</h3>
        <img class="detected-image" :src="image.detected_url" alt="检测结果">
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { ref, onMounted, type Ref } from 'vue'
import { SERVER_URL } from '@/components/handleApp'
import { useRouter } from 'vue-router'
import type { ImageDict, ImageSource } from '@/components/handleDetect'
import { ElMessage, ElMessageBox } from 'element-plus'

/**变量 */
// 展示情况
const showingHistory = ref(true)
const image = ref<ImageSource>({
  name: '',
  url: '',
  detected_url: '',
  model_name: ''
})
// 分页相关变量
const current_page = ref(1)
const total_count = ref(40)
const PAGE_SIZE = ref(4)
const tableData: Ref<ImageDict[]> = ref([])
// 路由
const router = useRouter()

/**函数 */
/**
 * 分页变化时更新页码和展示数据
 * @param newVal 新页码
 */
function handlePageChange(newVal: number) {
  current_page.value = newVal
  updatePageData(newVal)
}

/**
 * 获取总记录数量
 */
function updateTotalCount() {
  axios.get(`${SERVER_URL}/detect/get-page-history/`, {
    params: {
      page_size: PAGE_SIZE.value,
      current_page: 0,  // 要获取总数量时，当前页码为0
    }
  })
    .then((res) => {
      total_count.value = res.data.count
    })
    .catch((err) => {
      console.log(err)
    })
}

/**
 * 更新分页数据
 * @param newPage 新页码
 */
function updatePageData(newPage: number) {
  axios.get(`${SERVER_URL}/detect/get-page-history/`, {
    params: {
      page_size: PAGE_SIZE.value,
      current_page: current_page.value,
    }
  })
    .then((res) => {
      tableData.value = res.data.list
      for (const item of tableData.value) {
        item.encode_img = `data:image/jpeg;base64,${item.encode_img}`
        item.encode_detected_img = `data:image/jpeg;base64,${item.encode_detected_img}`
      }
    })
    .catch((err) => {
      tableData.value = []
      console.log(err)
    })
}

/**
 * 行点击事件
 * @param row 行数据
 */
function handleRowClick(row: ImageDict, column: any, event: any) {
  image.value.name = row.name
  image.value.url = row.encode_img
  image.value.detected_url = row.encode_detected_img || ''
  image.value.model_name = row.model_name || ''
  showingHistory.value = false  // 切换到展示选择的历史信息
}

/**
 * 删除记录
 * @param row 行数据
 */
function deleteRow(row: ImageDict, event: MouseEvent) {
  event.stopPropagation()
  event.preventDefault()
  ElMessageBox.confirm(
    '此记录将被永久删除，请确认。',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const ret = await axios.delete(`${SERVER_URL}/detect/delete-history/`, {
        params: {
          img_name: row.name
        }
      })
      if (ret.status === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        updateTotalCount()
        updatePageData(current_page.value)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


onMounted(() => {
  showingHistory.value = true
  updateTotalCount()
  updatePageData(current_page.value)
})
</script>

<style scoped>
.image-container {
  display: flex;
  /* 使用flexbox布局 */
  gap: 20px;
  /* 图片之间的间距 */
}

.image-item {
  display: flex;
  flex-direction: column;
  /* 使标签和图片垂直排列 */
  align-items: center;
  /* 居中对齐 */
}

.detect-image,
.detected-image {
  margin-top: 10px;
  width: 60%;
  height: auto;
}
</style>